package com.hmdp.service.impl;

import ch.qos.logback.classic.spi.EventArgUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    private final IUserService userService;
    private final StringRedisTemplate stringRedisTemplate;
    private final IFollowService followService;

    @Override
    public Result queryBlogById(Long id) {
        Blog blog = this.getById(id);
        if(blog == null){
            return Result.fail("笔记不存在");
        }
        queryBlogUser(blog);
        IsLiked(blog);
        return Result.ok(blog);
    }

    private void IsLiked(Blog blog) {
        String key = "blog:liked:" + blog.getId();
        UserDTO userDTO = UserHolder.getUser();
        if (userDTO == null){
            return;
        }
        Long userId = UserHolder.getUser().getId();
        //1.利用redis中的set集合不可重复性去实现点赞功能，判断用户是否点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);
    }

    @Override
    public void updateLiked(Long id) {
        String key = "blog:liked:" + id;
        Long userId = UserHolder.getUser().getId();
        //1.利用redis中的set集合不可重复性去实现点赞功能，判断用户是否点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score == null){
            //2.如果没有点赞，则点赞
            boolean update = update().setSql("liked = liked + 1").eq("id", id).update();
            if (update){
                //3.如果更新成功，则将数据保存到redis中
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
            }
        }else{
            //4.如果已经点赞，则取消点赞
            boolean update = update().setSql("liked = liked - 1").eq("id", id).update();
            if (update){
                //5.如果更新成功，则将数据保存到redis中
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }
        }
    }

    @Override
    public Result queryHotBlog(Integer current) {
        Page<Blog> page = this.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            this.queryBlogUser(blog);
          this.IsLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogLikes(Long id) {
        String key = "blog:liked:" + id;
        //查询top5的点赞用户id
        Set<String> stringId = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (stringId == null || stringId.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        log.info("点赞用户id：{}",stringId);
        //将用户id转为long型
        List<Long>  userIds = stringId.stream() .map(Long::valueOf) .collect(Collectors.toList());;
        log.info("用户id：{}",userIds.get(0));
        //根据用户id查询用户
        String join = StrUtil.join(",", userIds);
        List<User> users = userService.query().in("id",userIds)
                .last("ORDER BY FIELD(id,"+join+")").list();
        //返回用户信息
        return Result.ok(users);
    }

    @Override
    public Result saveBlog(Blog blog) {
        //1. 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        //2. 保存探店博文
        boolean isSuccess = save(blog);
        //3.判断是否新增笔记成功
        if(!isSuccess){
            return Result.fail("新增笔记失败");
        }
        //4.推送给所有粉丝
        //4.1 查询当前登录用户所有粉丝 select * from tb_follow where follow_id = ? userId
        List<Follow> followsFens = followService.lambdaQuery().eq(Follow::getId, user.getId()).list();
        //4.2对用户粉丝进行遍历
       for (Follow followsFen : followsFens) {
           //4.3推送消息给粉丝
           String key = "feed:"+followsFen.getUserId();
           //4.4向粉丝的收件箱中添加消息
           stringRedisTemplate.opsForZSet().add(key,followsFen.getId().toString(),System.currentTimeMillis());
       }
        //4，3每个粉丝拥有独立的收件箱，向每一个粉丝收件箱发送消息
        // .返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //1.获取用户信息
        UserDTO user = UserHolder.getUser();
        Long userId = user.getId();
        //2.准备参数从redis中查询收件箱
        String key = "feed:"+userId;
        //3.查询收件箱 max:这次的最大时间戳 offset:偏移量，上一次最小时间戳相同值  count：每一页查询数量 min:最小值
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if (typedTuples == null || typedTuples.isEmpty()){
            return Result.ok();
        }
         List<Long> list = new ArrayList<>(typedTuples.size());
           long minTime = 0;
           int os = 1;
        //3.遍历收件箱
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            //3.1获取id
            list.add(Long.valueOf(tuple.getValue()));
            //3.2获取时间戳
            Double score = tuple.getScore();
            //3.3将score转换为long型
            long time = score.longValue();
            if (time == minTime){
                os++;
            }else {
                minTime = time;
                os=1;
            }
        }
        //4.根据id查询blog
        String join = StrUtil.join(",", list);
        List<Blog> blogs = query().in("id", list).last("ORDER BY FIELD(id," + join + ")").list();
        for (Blog blog : blogs) {
            //5.查询blog有关的用户
            queryBlogUser(blog);
            //6.查询blog是否被点赞
            IsLiked(blog);
        }
        //5.封装并返回
        ScrollResult result = new ScrollResult();
        result.setList(blogs);
        result.setOffset(os);
        result.setMinTime(minTime);
        return Result.ok(result);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
